import axios from "axios";
import {Toast} from "vant";
// css 中 @font-face 已定义好
import FontFaceObserver from 'fontfaceobserver'
import color from "@/views/color";

export default {
    data() {
        return {
            canvas: null,
            tabsList2: [],
            dataList2: [],
            funcList: [
                // {
                //     id: '1',
                //     mame: '一键清除',
                //     img: require('@/assets/image/clear.png'),
                //     select_img: require('@/assets/image/clear_active.png'),
                // },
                {
                    id: '2',
                    mame: '素材',
                    img: require('@/assets/image/sucai.png'),
                    select_img: require('@/assets/image/sucai_active.png'),
                },
                {
                    id: '3',
                    mame: '照片上传',
                    img: require('@/assets/image/upload_img.png'),
                    select_img: require('@/assets/image/upload_img_active.png'),
                },
                {
                    id: '4',
                    mame: '文字',
                    img: require('@/assets/image/text.png'),
                    select_img: require('@/assets/image/text_active.png'),
                },
            ],
            funcList3: [
                {
                    id: '1',
                    mame: '删除',
                    img: require('@/assets/image/clear.png'),
                    select_img: require('@/assets/image/clear_active.png'),
                },
                {
                    id: '2',
                    mame: '编辑',
                    img: require('@/assets/image/sucai.png'),
                    select_img: require('@/assets/image/sucai_active.png'),
                },
                {
                    id: '3',
                    mame: '字体',
                    img: require('@/assets/image/font.png'),
                    select_img: require('@/assets/image/font_active.png'),
                },
                {
                    id: '4',
                    mame: '字号',
                    img: require('@/assets/image/text.png'),
                    select_img: require('@/assets/image/text_active.png'),
                },
                {
                    id: '5',
                    mame: '颜色',
                    img: require('@/assets/image/color.png'),
                    select_img: require('@/assets/image/color_active.png'),
                },
                {
                    id: '6',
                    mame: '前面',
                    img: require('@/assets/image/top.png'),
                    select_img: require('@/assets/image/top_active.png'),
                },
                {
                    id: '7',
                    mame: '背面',
                    img: require('@/assets/image/top.png'),
                    select_img: require('@/assets/image/top_active.png'),
                },

            ],
            // 字体
            tabActiveName33: null,
            /**
             * 素材配置
             */
            show5: false,
            sucaiConfigFuncList: [
                {
                    id: '1',
                    mame: '删除',
                    img: require('@/assets/image/clear.png'),
                    select_img: require('@/assets/image/clear_active.png'),
                },
                {
                    id: '2',
                    mame: '前面',
                    img: require('@/assets/image/top.png'),
                    select_img: require('@/assets/image/top_active.png'),
                },
                {
                    id: '3',
                    mame: '背面',
                    img: require('@/assets/image/top.png'),
                    select_img: require('@/assets/image/top_active.png'),
                },
                {
                    id: '4',
                    mame: '裁剪',
                    img: require('@/assets/image/clip.png'),
                    select_img: require('@/assets/image/clip_active.png'),
                },
            ],
            currentActiveSucaiConfig: '',
            /**
             * 图片裁剪
             */
            show6: false,
            currentClipImageUrl: '',
            fixedNumber: [],
            textNode: {},
            show2: false,
            show3: false,
            show4: false,
            /**
             * 文本颜色
             */
            tabsList34: color.map((el,index) => {
                return {
                    id: index,
                    name: el
                }
            })
        }
    },
    mounted() {
        this.getFontList()
    },
    methods: {
        handleClearFocus() {
            const that = this
            that.canvas.activeLayer.clear()
            that.canvas.render(true)
            that.textNode = {
                text: '',
                font: {
                    fontSize: 14,
                    textAlign: 'center'
                }
            }
            that.show2 = false
            that.show3 = false
            that.show5 = false
            that.show6 = false
        },
        handleReset(d) {
            if (d === 'left') {
                this.canvas.undo()
            } else {
                this.canvas.redo()
            }
        },
        getSucaiType() {
            axios({
                method: 'GET',
                url: this.baseUrl + '/api/v1/card/element-themes',
                headers: {
                    'X-UNI-TOKEN': localStorage.getItem('token'),
                },
            }).then(res => {
                if (res.data.code === 200) {
                    this.tabsList2 =res.data.data.map(el => {
                        return {
                            id: el.themeId,
                            name: el.name
                        }
                    })
                    if(this.tabsList2.length) {
                        this.getSucaiList(this.tabsList2[0].id)
                    }
                } else {
                    Toast.fail(res.data.msg)
                }
            })
        },
        getSucaiList(themeId) {
            Toast.loading({
                message: '加载中',
                duration: 0
            })
            axios({
                method: 'GET',
                url: this.baseUrl +`/api/v1/card/elements/${themeId}`,
                headers: {
                    'X-UNI-TOKEN': localStorage.getItem('token'),
                },
                params: {
                    pageNo: 1,
                    pageSize: 99
                }
            }).then(res => {
                Toast.clear()
                if (res.data.code === 200) {
                    this.dataList2 =res.data.data.map(el => {
                        return {
                            ...el,
                            id: el.elementId,
                            imgUrl: el.elementUrl
                        }
                    })
                } else {
                    Toast.fail(res.data.msg)
                }
            })
        },
        getFontList() {
            Toast.loading({
                message: '加载中',
                duration: 0
            })
            axios({
                method: 'GET',
                url: this.baseUrl +`/api/v1/card/fonts`,
                headers: {
                    'X-UNI-TOKEN': localStorage.getItem('token'),
                },
                params: {
                    pageNo: 1,
                    pageSize: 99
                }
            }).then(res => {
                if (!res.data.data || !res.data.data.length) return
                this.tabsList33 = res.data.data || []

                let fonts = this.tabsList33
                for (var i = 0; i < fonts.length; i++) {
                    let style = document.createElement('style');
                    style.type = "text/css";
                    let text = ` @font-face {
                  font-family:'${fonts[i].name}';
                  src:url('${ fonts[i].url}')
                  }`
                    style.innerText = text;
                    document.getElementsByTagName('head')[0].appendChild(style)
                }
            })

        },
        uploadImage() {
            let imgBase64 = this.canvas.toImage()
            console.log('imgBase64',imgBase64)
            if (typeof imgBase64 === 'string') {
                imgBase64 = imgBase64.replace('data:image/png;base64,', '')
            }
            let imgBase64Arr = imgBase64.split('')
            let imgBase64Arr2 = []
            while (imgBase64Arr.length) {
                imgBase64Arr2.push(imgBase64Arr.splice(0,60000).join(''))
            }
            console.log('imgBase64Arr2', imgBase64Arr2)
            return new Promise((resolve,reject) => {
                axios({
                    method: 'POST',
                    url: this.baseUrl + '/api/v1/oss/images/base64/upload',
                    headers: {
                        'X-UNI-TOKEN': localStorage.getItem('token'),
                    },
                    data: {
                        "destFileName": "",
                        "imgBase64": imgBase64Arr2,
                        "imgPostfix": ""
                    }
                }).then(res => {
                    if (res.data.code === 200) {
                        Toast.success('保存成功')
                        resolve(res.data.data.fileUrl)
                    } else {
                        Toast.fail(res.data.msg)
                    }
                }).catch((err) => {
                    Toast.fail(err || '请求出错')
                })

            })
        },
        loadfont(fontName){
            Toast.loading({
                message: '加载中',
                duration: 0
            })
            console.time("字体加载用时")
            return new Promise((resolve,reject) => {
                new FontFaceObserver(fontName).load(null, 30 * 1000).then(() =>{
                    Toast.clear()
                    resolve()
                    console.timeEnd("字体加载用时")
                }).catch(err => {
                    Toast.fail('字体加载失败')
                })
            })
        },
        /**
         * 素材配置
         */
        handleChangeSucaiConfigFunc(item) {
            this.currentActiveSucaiConfig = item.id
            switch (item.id) {
                case '1':
                    this.canvas.delete()
                    break
                // 前面
                case '2':
                    if (this.canvas.activeLayer.pens.length) {
                        this.canvas.top(this.canvas.activeLayer.pens[0])
                        this.canvas.render()
                    }
                    break
                // 背面
                case '3':
                    if (this.canvas.activeLayer.pens.length) {
                        this.canvas.bottom(this.canvas.activeLayer.pens[0])
                        this.canvas.render()
                    }
                    break
                // 裁剪
                case '4':
                    if (this.canvas.activeLayer.pens.length) {
                        const pen = this.canvas.activeLayer.pens[0]
                       this.show6 = true
                        this.currentClipImageUrl = pen.image
                        this.fixedNumber =  [pen.img.width, pen.img.height]
                    }
                    break
            }
        },
        /**
         * 图片裁剪
         */
        handleGetClipImageRes(url){
            this.textNode.image = url
            this.show6 = false
            this.canvas.render()
        },
     }
}
